<template>
  <div class="user-groups-page">
    <div class="page-header">
      <h2>用户组管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加用户组
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="组名">
          <el-input v-model="searchForm.name" placeholder="请输入组名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadUserGroups">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户组列表 -->
    <el-card>
      <el-table :data="userGroups" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="组名" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="created_at" label="创建时间">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320">
          <template #default="{ row }">
            <el-button size="small" type="success" @click="manageMembers(row)">管理成员</el-button>
            <el-button size="small" type="warning" @click="manageRoles(row)">管理角色</el-button>
            <el-button size="small" type="primary" @click="editUserGroup(row)">编辑</el-button>

            <el-dropdown @command="(command) => handleMoreAction(command, row)" style="margin-left: 8px;">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="copy">复制用户组</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除用户组</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadUserGroups"
          @current-change="loadUserGroups"
        />
      </div>
    </el-card>
    <!-- 添加/编辑用户组对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingUserGroup ? '编辑用户组' : '添加用户组'"
      width="600px"
    >
      <el-form
        ref="userGroupFormRef"
        :model="userGroupForm"
        :rules="userGroupRules"
        label-width="100px"
      >
        <el-form-item label="组名" prop="name">
          <el-input v-model="userGroupForm.name" placeholder="请输入组名" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="userGroupForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveUserGroup" :loading="saving">
          {{ editingUserGroup ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 管理成员对话框 -->
    <el-dialog v-model="showMembersDialog" title="管理用户组成员" width="900px">
      <div class="members-management">
        <div class="section">
          <h4>当前成员</h4>
          <el-table :data="currentMembers" v-loading="loadingMembers" max-height="300" @selection-change="handleCurrentMembersSelection">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="username" label="用户名">
              <template #default="{ row }">
                <UserDisplay :user="row" />
              </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="first_name" label="姓名">
              <template #default="{ row }">
                {{ getFullName(row) }}
              </template>
            </el-table-column>
          </el-table>
          <div class="action-buttons">
            <el-button type="danger" @click="removeSelectedMembers" :disabled="selectedCurrentMembers.length === 0">
              移除选中用户
            </el-button>
          </div>
        </div>

        <div class="section">
          <h4>添加新成员</h4>
          <el-input v-model="memberSearchKeyword" placeholder="搜索用户" @input="searchAvailableUsers" style="margin-bottom: 10px;" />
          <el-table :data="availableUsers" v-loading="loadingAvailableUsers" max-height="300" @selection-change="handleAvailableUsersSelection">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="username" label="用户名">
              <template #default="{ row }">
                <UserDisplay :user="row" />
              </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" />
            <el-table-column label="姓名">
              <template #default="{ row }">
                {{ getFullName(row) }}
              </template>
            </el-table-column>
          </el-table>
          <div class="action-buttons">
            <el-button type="primary" @click="addSelectedMembers" :disabled="selectedAvailableUsers.length === 0">
              添加选中用户
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 管理角色对话框 -->
    <el-dialog v-model="showRolesDialog" title="管理用户组角色" width="600px">
      <el-form label-width="100px">
        <el-form-item label="分配角色">
          <el-select v-model="selectedRoleIds" multiple placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="role in allRoles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showRolesDialog = false">取消</el-button>
        <el-button type="primary" @click="saveGroupRoles" :loading="savingRoles">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowDown } from '@element-plus/icons-vue'
import { userManagementAPI } from '@/api/userManagement'
import UserDisplay from '@/components/UserDisplay.vue'

// 防抖函数
function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 对话框控制
const showAddDialog = ref(false)
const showMembersDialog = ref(false)
const showRolesDialog = ref(false)
const editingUserGroup = ref(null)
const currentUserGroup = ref(null)

// 响应式数据
const userGroups = ref([])
const currentMembers = ref([])
const availableUsers = ref([])
const allRoles = ref([])
const selectedRoleIds = ref([])
const loading = ref(false)
const saving = ref(false)
const loadingMembers = ref(false)
const loadingAvailableUsers = ref(false)
const savingRoles = ref(false)

// 成员管理相关
const memberSearchKeyword = ref('')
const selectedCurrentMembers = ref([])
const selectedAvailableUsers = ref([])

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 用户组表单
const userGroupForm = reactive({
  name: '',
  description: ''
})

// 表单引用
const userGroupFormRef = ref()

// 表单验证规则
const userGroupRules = {
  name: [
    { required: true, message: '请输入组名', trigger: 'blur' },
    { min: 2, max: 100, message: '组名长度在 2 到 100 个字符', trigger: 'blur' }
  ]
}

// 方法
const loadUserGroups = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...searchForm
    }

    const response = await userManagementAPI.getUserGroups(params)
    userGroups.value = response.results
    pagination.total = response.count
  } catch (error) {
    console.error('加载用户组失败:', error)
    ElMessage.error('加载用户组失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchForm.name = ''
  pagination.page = 1
  loadUserGroups()
}

const editUserGroup = (userGroup) => {
  editingUserGroup.value = userGroup
  userGroupForm.name = userGroup.name
  userGroupForm.description = userGroup.description
  showAddDialog.value = true
}

const saveUserGroup = async () => {
  if (!userGroupFormRef.value) return

  try {
    await userGroupFormRef.value.validate()
    saving.value = true

    if (editingUserGroup.value) {
      await userManagementAPI.updateUserGroup(editingUserGroup.value.id, userGroupForm)
      ElMessage.success('用户组更新成功')
    } else {
      await userManagementAPI.createUserGroup(userGroupForm)
      ElMessage.success('用户组创建成功')
    }

    showAddDialog.value = false
    resetForm()
    loadUserGroups()
  } catch (error) {
    console.error('保存用户组失败:', error)
    ElMessage.error('保存用户组失败')
  } finally {
    saving.value = false
  }
}

const deleteUserGroup = async (userGroup) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户组 "${userGroup.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await userManagementAPI.deleteUserGroup(userGroup.id)
    ElMessage.success('用户组删除成功')
    loadUserGroups()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户组失败:', error)
      ElMessage.error('删除用户组失败')
    }
  }
}

// 更多操作处理
const handleMoreAction = (command, userGroup) => {
  switch (command) {
    case 'copy':
      copyUserGroup(userGroup)
      break
    case 'delete':
      deleteUserGroup(userGroup)
      break
  }
}

// 复制用户组
const copyUserGroup = (userGroup) => {
  editingUserGroup.value = null
  userGroupForm.name = `${userGroup.name} - 副本`
  userGroupForm.description = userGroup.description
  showAddDialog.value = true
}

// 成员管理相关方法
const manageMembers = async (userGroup) => {
  currentUserGroup.value = userGroup
  await loadCurrentMembers()
  await loadAvailableUsers()
  showMembersDialog.value = true
}

const loadCurrentMembers = async () => {
  if (!currentUserGroup.value) return

  loadingMembers.value = true
  try {
    const response = await userManagementAPI.getUserGroupUsers(currentUserGroup.value.id)
    currentMembers.value = response
  } catch (error) {
    console.error('加载当前成员失败:', error)
    ElMessage.error('加载当前成员失败')
  } finally {
    loadingMembers.value = false
  }
}

const loadAvailableUsers = async () => {
  loadingAvailableUsers.value = true
  try {
    const response = await userManagementAPI.getUsers({ search: memberSearchKeyword.value })
    // 过滤掉已经在用户组中的用户
    const currentMemberIds = currentMembers.value.map(user => user.id)
    availableUsers.value = (response.results || response).filter(user => !currentMemberIds.includes(user.id))
  } catch (error) {
    console.error('加载可用用户失败:', error)
    ElMessage.error('加载可用用户失败')
  } finally {
    loadingAvailableUsers.value = false
  }
}

const searchAvailableUsers = debounce(() => {
  loadAvailableUsers()
}, 300)

const handleCurrentMembersSelection = (selection) => {
  selectedCurrentMembers.value = selection
}

const handleAvailableUsersSelection = (selection) => {
  console.log('可用用户选择变化:', selection)
  selectedAvailableUsers.value = selection
  console.log('当前选中的可用用户数量:', selectedAvailableUsers.value.length)
}

const addSelectedMembers = async () => {
  if (selectedAvailableUsers.value.length === 0) return

  try {
    const userIds = selectedAvailableUsers.value.map(user => user.id)
    await userManagementAPI.addUsersToGroup(currentUserGroup.value.id, { user_ids: userIds })
    ElMessage.success('用户添加成功')
    await loadCurrentMembers()
    await loadAvailableUsers()
    selectedAvailableUsers.value = []
  } catch (error) {
    console.error('添加用户失败:', error)
    ElMessage.error('添加用户失败')
  }
}

const removeSelectedMembers = async () => {
  if (selectedCurrentMembers.value.length === 0) return

  try {
    const userIds = selectedCurrentMembers.value.map(user => user.id)
    await userManagementAPI.removeUsersFromGroup(currentUserGroup.value.id, { user_ids: userIds })
    ElMessage.success('用户移除成功')
    await loadCurrentMembers()
    await loadAvailableUsers()
    selectedCurrentMembers.value = []
  } catch (error) {
    console.error('移除用户失败:', error)
    ElMessage.error('移除用户失败')
  }
}

// 角色管理相关方法
const manageRoles = async (userGroup) => {
  currentUserGroup.value = userGroup
  await loadAllRoles()
  await loadGroupRoles()
  showRolesDialog.value = true
}

const loadAllRoles = async () => {
  try {
    const response = await userManagementAPI.getRoles()
    allRoles.value = response.results || response
    console.log('所有角色数据:', allRoles.value) // 调试日志
  } catch (error) {
    console.error('加载角色失败:', error)
    ElMessage.error('加载角色失败')
  }
}

const loadGroupRoles = async () => {
  if (!currentUserGroup.value) return

  try {
    const response = await userManagementAPI.getUserGroupRoles(currentUserGroup.value.id)
    console.log('用户组角色数据:', response) // 调试日志

    // 处理响应数据，确保正确提取角色ID
    if (Array.isArray(response)) {
      selectedRoleIds.value = response.map(item => item.role)
    } else if (response.results) {
      selectedRoleIds.value = response.results.map(item => item.role)
    } else {
      selectedRoleIds.value = []
    }

    console.log('选中的角色IDs:', selectedRoleIds.value) // 调试日志
  } catch (error) {
    console.error('加载用户组角色失败:', error)
    ElMessage.error('加载用户组角色失败')
    selectedRoleIds.value = []
  }
}

const saveGroupRoles = async () => {
  if (!currentUserGroup.value) return

  savingRoles.value = true
  try {
    await userManagementAPI.assignRolesToGroup(currentUserGroup.value.id, { role_ids: selectedRoleIds.value })
    ElMessage.success('角色分配成功')
    showRolesDialog.value = false
    await loadUserGroups() // 重新加载用户组列表
  } catch (error) {
    console.error('角色分配失败:', error)
    ElMessage.error('角色分配失败')
  } finally {
    savingRoles.value = false
  }
}

const getFullName = (user) => {
  return user.full_name || user.username || '-'
}

const resetForm = () => {
  userGroupForm.name = ''
  userGroupForm.description = ''
  editingUserGroup.value = null
  if (userGroupFormRef.value) {
    userGroupFormRef.value.resetFields()
  }
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadUserGroups()
})
</script>

<style scoped>
.user-groups-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.members-management {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.section {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
}

.section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.action-buttons {
  margin-top: 10px;
  text-align: right;
}
</style>
